package com.foreknow.web;


import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.foreknow.entity.User;
import com.foreknow.service.UserService;
import com.foreknow.utils.Constance;
import com.foreknow.utils.TokenUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import io.swagger.annotations.ApiOperation;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.foreknow.utils.downLoadExcel.downLoadExcel;

@RestController
@RequestMapping("/user")
public class UserController{

    @Autowired
    private UserService userService;

    //  登录验证 参数 username password
    @ApiOperation("登录验证")
    @RequestMapping(value = "/login",method = RequestMethod.POST)
    public String login(@RequestBody Map<String,Object> para) throws JsonProcessingException {
    //    获取用户登录信息
        String username=(String)para.get("username");
        String password=(String)para.get("password");

        User user = new User();
        user.setUsername(username);
        user.setPassword(password);
        User loginuser = userService.login(user);

        HashMap<String,Object> hs=new HashMap<>();
        ObjectMapper objectMapper=new ObjectMapper();

        //登录成功
        if (loginuser!=null){
            //  生成token信息
            String token= TokenUtil.sign(user);
            user.setToken(token);
            //    hs.put("token",token);
            hs.put("data",user);
            hs.put("meta",new Constance("msg",200));

            return objectMapper.writeValueAsString(hs);
        }
        //登录失败
        hs.put("meta",new Constance("msg",404));
        return objectMapper.writeValueAsString(hs);


  }

    //根据条件分页查询用户信息 参数 查询条件user对象 页数pageNum 数据条数pageSize
    @ApiOperation("根据条件分页查询用户信息")
    @RequestMapping(value = "/listUsers")
    @ResponseBody
    public String findByPageByCondition(@RequestBody Map<String,Object> para) throws JsonProcessingException{

        HashMap<String,Object> hs=new HashMap<>();
        ObjectMapper objectMapper=new ObjectMapper();
        User user = new User();
        if(para.get("username")!=null){ user.setUsername((String)para.get("username"));}
        if(para.get("realname")!=null){ user.setRealname((String)para.get("realname"));}
        if(para.get("usetype")!=null){ user.setUsetype((Integer) para.get("usetype"));}
        if(para.get("isscheduling")!=null){user.setIsscheduling((String) para.get("isscheduling"));}
        if(para.get("registleid")!=null){ user.setRegistleid((Integer)para.get("registleid"));}
        if(para.get("doctitleid")!=null){ user.setDoctitleid((Integer)para.get("doctitleid"));}
        if(para.get("deptid")!=null){  user.setDeptid((Integer)para.get("deptid"));}

        //按条件查询 且不分页
        if (para.get("pageNum")==null && para.get("pageSize")==null){

            List<User> list = userService.selectByCondition(user);
            //判断是否成功
            if (list.size()>0){
                hs.put("list",list);
                hs.put("meta",new Constance("msg",200));
                return objectMapper.writeValueAsString(hs);
            }
            //失败
            hs.put("meta",new Constance("msg",404));
            return objectMapper.writeValueAsString(hs);

        }
        Integer pageNum = (Integer)para.get("pageNum");
        Integer pageSize =  (Integer)para.get("pageSize");

        PageHelper.startPage(pageNum,pageSize);
        List<User> users = userService.selectByCondition(user);
        PageInfo<User> pageInfo = new PageInfo<User>(users);


        hs.put("meta",new Constance("msg",200));
        hs.put("info",pageInfo);

        return objectMapper.writeValueAsString(hs);

    }


    //模板下载
    @ApiOperation("模板下载")
    @RequestMapping(value="/downloadExcel")
    public ResponseEntity<Resource> excel2007Export(HttpServletResponse response, HttpServletRequest request) {
        try {
            ClassPathResource cpr = new ClassPathResource("/templates/"+"model.xlsx");
            InputStream is = cpr.getInputStream();
            Workbook workbook = new HSSFWorkbook(is);
            String fileName = "model.xlsx";
            downLoadExcel(fileName, response, workbook);

        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return new ResponseEntity<Resource>(HttpStatus.OK);


    }

    //根据用户主键查询用户信息 参数 id
    @ApiOperation("根据用户主键查询用户信息")
    @RequestMapping(value = "/findUserById")
    @ResponseBody
    public String findUserById(@RequestBody Map<String,Object> para) throws JsonProcessingException{

        Integer id = (Integer)para.get("id");
        User user = userService.selectByPrimaryKey(id);
        HashMap<String,Object> hs=new HashMap<>();
        ObjectMapper objectMapper=new ObjectMapper();
        //判断是否成功
        if (user!=null){
            hs.put("user",user);
            hs.put("meta",new Constance("msg",200));
            return objectMapper.writeValueAsString(hs);
        }
        //失败
        hs.put("meta",new Constance("msg",404));

        return objectMapper.writeValueAsString(hs);

    }

    //  添加一个用户信息 参数 user对象
    @ApiOperation("添加一个用户信息")
    @RequestMapping("/saveOneUser")
    public String saveOneUser(@RequestBody Map<String,Object> para) throws JsonProcessingException{

        User user = new User();
        if(para.get("username")!=null){ user.setUsername((String)para.get("username"));}
        if(para.get("password")!=null){ user.setPassword((String)para.get("password"));}
        if(para.get("realname")!=null){ user.setRealname((String)para.get("realname"));}
        if(para.get("usetype")!=null){ user.setUsetype((Integer) para.get("usetype"));}
        if(para.get("doctitleid")!=null){ user.setDoctitleid((Integer)para.get("doctitleid"));}
        if(para.get("isscheduling")!=null){ user.setIsscheduling((String)para.get("isscheduling"));}
        if(para.get("deptid")!=null){  user.setDeptid((Integer)para.get("deptid"));}
        if(para.get("registleid")!=null){  user.setRegistleid((Integer)para.get("registleid"));}
        user.setDelmark(1);
        int insert = userService.insert(user);
        HashMap<String,Object> hs=new HashMap<>();
        ObjectMapper objectMapper=new ObjectMapper();

        //判断是否成功
        if (insert==1){

            hs.put("meta",new Constance("msg",200));

            return objectMapper.writeValueAsString(hs);
        }
        //失败
        hs.put("meta",new Constance("msg",404));
        return objectMapper.writeValueAsString(hs);

    }

    //批量添加用户信息 参数 文件
    @ApiOperation("批量添加用户信息")
    @RequestMapping("/saveUserBatch")
    @ResponseBody
    public String saveUserBatch(@RequestParam("excelFile") MultipartFile excelFile)throws JsonProcessingException {
        String name = excelFile.getOriginalFilename();
        HashMap<String, Object> hs = new HashMap<>();
        ObjectMapper objectMapper = new ObjectMapper();
        try {
            Map<String, Object> map = userService.excelToList(excelFile.getInputStream());

            Integer flag = (Integer) map.get("flag");
            List<String> errorList = new ArrayList<>();
            //失败
            if (map.get("errorList")!=null){
                hs.put("meta", new Constance("msg", 404));
                hs.put("flag",flag);
                errorList = (List<String>) (map.get("errorList"));
                hs.put("errorList",errorList);
                return objectMapper.writeValueAsString(hs);
            }else if (flag==0){
                hs.put("flag",flag);
                hs.put("meta", new Constance("msg", 404));
                return objectMapper.writeValueAsString(hs);
            }else {
                hs.put("meta", new Constance("msg", 200));
                return objectMapper.writeValueAsString(hs);
            }

        }catch (Exception e) {
            e.printStackTrace();
            //失败
            hs.put("meta", new Constance("msg", 404));
            return objectMapper.writeValueAsString(hs);

        }
    }


    //添加时用户名验证  参数 username
    @ApiOperation("添加时用户名验证")
    @RequestMapping("/findValidUserName")
    public String findValidUserName(@RequestBody Map<String,Object> para) throws JsonProcessingException{
        HashMap<String,Object> hs=new HashMap<>();
        ObjectMapper objectMapper=new ObjectMapper();
        if(para.get("username")!=null){
            User user = userService.selectByUserName((String) para.get("username"));
            //判断是否成功
            if (user!=null){
                hs.put("user",user);
                hs.put("meta",new Constance("msg",200));

                return objectMapper.writeValueAsString(hs);
            }
        }
        //失败
        hs.put("meta",new Constance("msg",404));
        return objectMapper.writeValueAsString(hs);

    }

    //修改用户信息 参数 User对象
    @ApiOperation("修改用户信息")
    @RequestMapping("/updateById")
    public String updateById(@RequestBody Map<String,Object> para) throws JsonProcessingException{
        HashMap<String,Object> hs=new HashMap<>();
        ObjectMapper objectMapper=new ObjectMapper();

        User user = new User();
        if(para.get("id")!=null){  user.setId((Integer)para.get("id"));}
        else{
            //失败
            hs.put("meta",new Constance("msg",404));
            return objectMapper.writeValueAsString(hs);
        }
        if(para.get("username")!=null){ user.setUsername((String)para.get("username"));}
        if(para.get("password")!=null){ user.setPassword((String)para.get("password"));}
        if(para.get("realname")!=null){ user.setRealname((String)para.get("realname"));}
        if(para.get("usetype")!=null){ user.setUsetype((Integer) para.get("usetype"));}
        if(para.get("doctitleid")!=null){ user.setDoctitleid((Integer)para.get("doctitleid"));}
        if(para.get("isscheduling")!=null){ user.setIsscheduling((String)para.get("isscheduling"));}
        if(para.get("deptid")!=null){  user.setDeptid((Integer)para.get("deptid"));}
        if(para.get("registleid")!=null){  user.setRegistleid((Integer)para.get("registleid"));}

        int i = userService.updateByPrimaryKeySelective(user);
        //判断是否成功
        if (i==1){
            hs.put("meta",new Constance("msg",200));

            return objectMapper.writeValueAsString(hs);
        }
        //失败
        hs.put("meta",new Constance("msg",404));
        return objectMapper.writeValueAsString(hs);

    }

    //删除一个用户信息 参数 用户id
    @ApiOperation("删除一个用户信息")
    @RequestMapping("/deleteUserById")
    public String deleteUserById(@RequestBody Map<String,Object> para) throws JsonProcessingException{

        Integer id = (Integer) para.get("id");
        int i = userService.deleteByPrimaryKeyByLogic(id);
        HashMap<String,Object> hs=new HashMap<>();
        ObjectMapper objectMapper=new ObjectMapper();

        //判断是否成功
        if (i==1){

            hs.put("meta",new Constance("msg",200));
            return objectMapper.writeValueAsString(hs);
        }
        //失败
        hs.put("meta",new Constance("msg",404));
        return objectMapper.writeValueAsString(hs);


    }

    //批量删除用户信息  参数 用户主键id集合
    @ApiOperation("批量删除用户信息")
    @RequestMapping("/deleteUserBatch")
    public String deleteUserBatch(@RequestBody Map<String,Object> para) throws JsonProcessingException{

        HashMap<String,Object> hs=new HashMap<>();
        ObjectMapper objectMapper=new ObjectMapper();
        if (para.get("idArray")==null){
            //失败
            hs.put("meta",new Constance("msg",404));
            return objectMapper.writeValueAsString(hs);
        }
        List<Integer> idArray = (ArrayList<Integer>) para.get("idArray");
        int i = userService.deleteByIdByLogicBatch(idArray);

        //判断是否成功
        if (i>0){
            hs.put("meta",new Constance("msg",200));

            return objectMapper.writeValueAsString(hs);
        }
        //失败
        hs.put("meta",new Constance("msg",404));
        return objectMapper.writeValueAsString(hs);

    }






}
